package middleware

import (
	"context"
	"github.com/gin-gonic/gin"
	"manager/auth"
	"strings"
)

var whiteList = map[string]struct{}{
	"/v1/app/promotionalImage/list":    {},
	"/v1/app/vehicleSkill/list":        {},
	"/v1/app/vehicleSkill/detail":      {},
	"/manager/v1/devices/erp/callback": {},
}

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		if _, ok := whiteList[c.FullPath()]; ok {
			c.Next()
			return
		}
		var (
			userId int64
		)
		authorization := c.GetHeader("Authorization")
		// 拆分token
		parts := strings.SplitN(authorization, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(401, gin.H{
				"code": 500,
				"data": nil,
				"msg":  "userid is illegal",
			})
			c.Abort()
			return
		}

		if options, err := auth.Extract(parts[1]); err != nil {
			c.JSON(401, gin.H{
				"code": 500,
				"data": nil,
				"msg":  "userid is illegal",
			})
			c.Abort()
			return
		} else {
			userId = options.UserID
		}
		//userId, err := strconv.Atoi(c.GetHeader("X-UserID"))
		//if err != nil || userId == 0 {
		//	c.JSON(401, gin.H{
		//		"code": 500,
		//		"data": nil,
		//		"msg":  "userid is illegal",
		//	})
		//	c.Abort()
		//	return
		//}

		ctx := c.Request.Context()
		// 用户
		ctx = context.WithValue(ctx, auth.AuthUserKey, int64(userId))
		// 平台os
		ctx = context.WithValue(ctx, auth.AuthOsKey, c.GetHeader("os"))
		c.Request = c.Request.WithContext(ctx)
		c.Next()
	}
}

var API_KEY = "9BQo161I6siXZoRK0zU3c"

func ApiKeyAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		apikey := c.GetHeader("x-api-key")
		if apikey != API_KEY {
			c.JSON(400, gin.H{
				"code": 500,
				"data": nil,
				"msg":  "x-api-key is invalid",
			})
			c.Abort()
		}
	}
}
